import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../store';

// 路由守卫组件接口
interface PrivateRouteProps {
  children: React.ReactNode;
  requiredPermissions?: string[];
}

// 路由守卫组件
const PrivateRoute: React.FC<PrivateRouteProps> = ({ 
  children, 
  requiredPermissions = [] 
}) => {
  const { isAuthenticated, userInfo } = useSelector((state: RootState) => state.auth);
  const location = useLocation();
  const pathname = location.pathname;

  // 如果未登录，且当前不是登录页，重定向到登录页
  if (!isAuthenticated && pathname !== '/login') {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 如果需要特定权限
  if (requiredPermissions.length > 0 && userInfo) {
    const hasPermission = requiredPermissions.some(permission =>
      userInfo.permissions.includes(permission) || userInfo.permissions.includes('*')
    );

    if (!hasPermission) {
      return <Navigate to="/403" replace />;
    }
  }

  return <>{children}</>;
};

export default PrivateRoute; 